package com.atguigu.controller;

import com.atguigu.dto.UserRanking;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
public class TestController {

    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping("/redisSave")
    public boolean save() throws InterruptedException {
        //redis中zset大key
        String redisKey = "ranking:user";

        redisTemplate.opsForZSet().add(redisKey, "zhangsan", 3 + (1 - (System.currentTimeMillis() / 1e13)));

        redisTemplate.opsForZSet().add(redisKey, "lisi", 2 + (1 - (System.currentTimeMillis() / 1e13)));

        Thread.sleep(10);

        redisTemplate.opsForZSet().add(redisKey, "wangwu", 5 + (1 - (System.currentTimeMillis() / 1e13)));

        Thread.sleep(2);

        redisTemplate.opsForZSet().add(redisKey, "qianliu", 5 + (1 - (System.currentTimeMillis() / 1e13)));

        return true;
    }

    @GetMapping("/getZset")
    public List<UserRanking> zset() {

        String redisKey = "ranking:user";

        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().reverseRangeWithScores(redisKey, 0, -1);

        List<UserRanking> userRankings  = new ArrayList<>();

        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            UserRanking userRanking = new UserRanking();
            userRanking.setUserId(typedTuple.getValue());
            userRanking.setRedisScore(typedTuple.getScore());
            userRankings.add(userRanking);
        }

        return userRankings;
    }
}
